package com.ruoyi.feike.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.file.ContractUploadUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.feike.domain.vo.ContractRecord;
import com.ruoyi.feike.mapper.ContractRecordMapper;
import com.ruoyi.feike.mapper.DealercodeContractFilingMapper;
import com.ruoyi.feike.service.IAnnualReviewyService;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.service.ISysPostService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.feike.domain.DealercodeContractFiling;
import com.ruoyi.feike.service.IDealercodeContractFilingService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 合同归档表Controller
 *
 * @author ruoyi
 * @date 2022-08-23
 */
@RestController
@RequestMapping("/feike/contractfiling")
public class DealercodeContractFilingController extends BaseController
{
    @Autowired
    private IDealercodeContractFilingService dealercodeContractFilingService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ContractRecordMapper contractRecordMapper;
    @Autowired
    private DealercodeContractFilingMapper dealercodeContractFilingMapper;

    @Autowired
    private IAnnualReviewyService annualReviewyService;

    @Autowired
    private ISysPostService postService;

    /**
     * 查询合同归档表列表
     */
    @GetMapping("/list")
    public TableDataInfo list(DealercodeContractFiling dealercodeContractFiling)
    {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        boolean flag = false;
        List<String> strings = postService.selectPostListByUserId1(loginUser.getUser().getUserId());
        for (String post : strings) {
            if(post.contains("op")){
                flag = true;
                break;
            }
        }
        startPage();
        List<DealercodeContractFiling> list = dealercodeContractFilingService.selectDealercodeContractFilingList(dealercodeContractFiling);
        for (DealercodeContractFiling contractFiling : list) {
            contractFiling.setFlag("2");
            contractFiling.setOpFlag("2");
            if(contractFiling.getContractLocation()!=null && contractFiling.getContractLocationHistory()!=null){
                if(contractFiling.getContractLocation().equals(contractFiling.getContractLocationHistory())){
                    contractFiling.setFlag("1");
                }
            }
            if(flag){
                contractFiling.setOpFlag("1");
            }

        }
        return getDataTable(list);
    }

    /**
     * 导出合同归档表列表
     */
    @Log(title = "合同归档表", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(DealercodeContractFiling dealercodeContractFiling)
    {
        List<DealercodeContractFiling> list = dealercodeContractFilingService.selectDealercodeContractFilingListExport(dealercodeContractFiling);
        ExcelUtil<DealercodeContractFiling> util = new ExcelUtil<DealercodeContractFiling>(DealercodeContractFiling.class);
        return util.exportExcel(list, "filing");
    }

    /**
     * 获取合同归档表详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(dealercodeContractFilingService.selectDealercodeContractFilingById(id));
    }

    /**
     * 新增合同归档表
     */
    @Log(title = "合同归档表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DealercodeContractFiling dealercodeContractFiling)
    {
        return toAjax(dealercodeContractFilingService.insertDealercodeContractFiling(dealercodeContractFiling));
    }

    /**
     * 修改合同归档表
     */
    @Log(title = "合同归档表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DealercodeContractFiling dealercodeContractFiling)
    {
        ContractRecord record = new ContractRecord();
        DealercodeContractFiling dealercodeContractFiling1 = dealercodeContractFilingMapper.selectDealercodeContractFilingById(dealercodeContractFiling.getId());
        record.setInstanceid(dealercodeContractFiling1.getInstanceId());
        record.setSector(dealercodeContractFiling1.getSector());
        record.setDealername(dealercodeContractFiling1.getDealerNameCN());
        record.setLimitType(dealercodeContractFiling1.getLimitType());
        List<ContractRecord> contractRecords = contractRecordMapper.selectContractRecordList(record);
        if(CollectionUtil.isNotEmpty(contractRecords)){
            for(ContractRecord c:contractRecords){
                ContractRecord contractRecord1 = new ContractRecord();
                contractRecord1.setOriginal(c.getOriginal());
                ContractRecord contractRecord = new ContractRecord();
                BeanUtils.copyProperties(c,contractRecord);
                c.setOriginal(dealercodeContractFiling.getFax());
                contractRecordMapper.updateContractRecord(c);
                ContractRecord contractRecord2 = new ContractRecord();
                contractRecord2.setOriginal(dealercodeContractFiling.getFax());
                annualReviewyService.saveDbLog("3","修改归档标识",null,null,contractRecord1,contractRecord2,"合同归档/Fax/Original");

            }
        }
        if(dealercodeContractFiling.getId()!=null){
            DealercodeContractFiling dealercodeContractFiling2 = dealercodeContractFilingService.selectDealercodeContractFilingById(dealercodeContractFiling.getId());
            if(dealercodeContractFiling.getFilingDate()==null){
                int i = dealercodeContractFilingService.updateDealercodeContractFiling2(dealercodeContractFiling);
            }else{
                int i = dealercodeContractFilingService.updateDealercodeContractFiling(dealercodeContractFiling);
            }
            DealercodeContractFiling dealercodeContractFiling3 = dealercodeContractFilingService.selectDealercodeContractFilingById(dealercodeContractFiling.getId());
            annualReviewyService.saveDbLog("3","修改归档信息",null,null,dealercodeContractFiling2,dealercodeContractFiling3,"合同归档/Fax/Original");

        }
        return toAjax(1);
    }

    /**
     * 删除所属的合同附件不删除表
     */
    @Log(title = "合同归档表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(dealercodeContractFilingService.deleteDealercodeContractFilingByIds(ids));
    }

    /**
     * 归档合同上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file, String sector, String contractName , String instanceId ,String contractUrl ,Long id) throws Exception
    {
        try
        {
            logger.info("文件上传开始,合同名称{}",contractName);
            String filename = file.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf("."));
            int length = contractUrl.length();
            String splicepdf = contractUrl.substring(8, length);
//            String filePathnew = RuoYiConfig.getProfile()+"/splicepdf/"+contractName+".pdf";
            String filePathnew = RuoYiConfig.getProfile()+splicepdf;
            int i = contractUrl.lastIndexOf("/");
            String substring = contractUrl.substring(0, i);
            String profile = substring.substring(8, substring.length());
            String ur = RuoYiConfig.getProfile() + profile + "/new";
            String history = RuoYiConfig.getProfile() + profile + "/new/" + contractName + ".pdf";
            String cun = "/profile"+profile + "/new/" + contractName + suffix;
            File file1 = new File(history);
            if(!file1.exists()&& !file1.isDirectory()) {
                //获取复制的文件
                /*File oldfile = new File(filePathnew);
                //文件输入流，用于读取要复制的文件
                FileInputStream fileInputStream = new FileInputStream(oldfile);*/
                //要生成的新文件（指定路径如果没有则创建）
                File newfile = new File(history);
                //获取父目录
                File fileParent = newfile.getParentFile();
                System.out.println(fileParent);
                //判断是否存在
                if (!fileParent.exists()) {
                    // 创建父目录文件夹
                    fileParent.mkdirs();
                }
         /*       //判断文件是否存在
                if (!newfile.exists()) {
                    //创建文件
                    newfile.createNewFile();
                }*/

         /*       //新文件输出流
                FileOutputStream fileOutputStream = new FileOutputStream(newfile);
                byte[] buffer = new byte[1024];
                int len;
                //将文件流信息读取文件缓存区，如果读取结果不为-1就代表文件没有读取完毕，反之已经读取完毕
                while ((len = fileInputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, len);
                    fileOutputStream.flush();
                }
                fileInputStream.close();
                fileOutputStream.close();*/

            }
            //上传新的合同删除旧的
            FileUtils.deleteFile(history);
            // 上传文件路径
            String filePath = RuoYiConfig.getProfile()+profile;
            System.out.println(contractName);

            // 上传并返回新文件名称
//            contractName = "123";
            String fileName = ContractUploadUtils.upload(ur, file ,contractName);
            DealercodeContractFiling dealercodeContractFiling = new DealercodeContractFiling();
            dealercodeContractFiling.setContractLocationHistory(cun);
            dealercodeContractFiling.setId(id);
            DealercodeContractFiling dealercodeContractFiling1 = dealercodeContractFilingMapper.selectDealercodeContractFilingById(id);

            //根据归档表查询报表，更新
            ContractRecord record = new ContractRecord();
            record.setInstanceid(dealercodeContractFiling1.getInstanceId());
            record.setDealername(dealercodeContractFiling1.getDealerNameCN());
            record.setSector(dealercodeContractFiling1.getSector());
            record.setLimitType(dealercodeContractFiling1.getLimitType());
            List<ContractRecord> contractRecords = contractRecordMapper.selectContractRecordList(record);
            if(CollectionUtil.isNotEmpty(contractRecords)){
                for(ContractRecord cr : contractRecords){
                    cr.setFileUrl(cun);
                    cr.setStatus("盖章");
                    contractRecordMapper.updateContractRecord(cr);
                }
            }

            dealercodeContractFilingMapper.updateDealercodeContractFiling(dealercodeContractFiling);
            DealercodeContractFiling dealercodeContractFiling2 = dealercodeContractFilingMapper.selectDealercodeContractFilingById(id);
            annualReviewyService.saveDbLog("3","修改归档合同信息",null,null,dealercodeContractFiling1,dealercodeContractFiling2,"合同归档/上传");

            String url = serverConfig.getUrl() + fileName;
            String originalFilename = file.getOriginalFilename();       // 文件的中文名
            System.out.println("fileName=="+fileName);
            System.out.println("cun=="+cun);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            ajax.put("originalFilename", originalFilename);
            //修改合同报表1Fax/Original值
//            DealercodeContractFiling dealercodeContractFiling = new DealercodeContractFiling();
//            dealercodeContractFiling.setInstanceId(instanceId);
//            dealercodeContractFiling.setContractName(contractName);
//            List<DealercodeContractFiling> dealercodeContractFilings = dealercodeContractFilingService.selectDealercodeContractFilingList(dealercodeContractFiling);
//            if(CollectionUtil.isNotEmpty(dealercodeContractFilings)){
//                ContractRecord record = new ContractRecord();
//                record.setInstanceid(instanceId);
//                record.setDealername(dealercodeContractFilings.get(0).getDealerNameCN());
//                record.setSector(dealercodeContractFilings.get(0).getSector());
//                record.setLimitType(dealercodeContractFilings.get(0).getLimitType());
//                List<ContractRecord> contractRecords = contractRecordMapper.selectContractRecordList(record);
//                if(CollectionUtil.isNotEmpty(contractRecords)){
//                    for(ContractRecord cr : contractRecords){
//                        cr.setOriginal("Original");
//                        contractRecordMapper.updateContractRecord(cr);
//                    }
//                }
//            }
            return ajax;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 子流程审批 修改type fax/Original
     */
    @GetMapping(value = "/updateType")
    public AjaxResult updateType(@RequestParam("subProcessId") String subProcessId, @RequestParam("type") String type) {

        //签回扫描or签回原件节点通过至合同确认时 调用该接口
//        String subProcessId = "";
//        String type = "";
        if (StringUtils.isNotEmpty(subProcessId) && StringUtils.isNotEmpty(type)) {

            List<DealercodeContractFiling> dealercodeContractFilings = dealercodeContractFilingMapper.selectDealercodeContractFilingBySubProcessId(subProcessId);

            //String instanceId = subProcessId.split("-")[0];

            for (DealercodeContractFiling dealercodeContractFiling : dealercodeContractFilings) {
                ContractRecord record = new ContractRecord();
                record.setDealername(dealercodeContractFiling.getDealerNameCN());
                record.setSector(dealercodeContractFiling.getSector());
                record.setLimitType(dealercodeContractFiling.getLimitType());
                record.setInstanceid(dealercodeContractFiling.getInstanceId());
                record.setOriginal(type);
                contractRecordMapper.updateOriginal(record);
                dealercodeContractFiling.setFax(type);
                dealercodeContractFilingMapper.updateDealercodeContractFiling(dealercodeContractFiling);
            }
            return AjaxResult.success();
        } else {
            return AjaxResult.error("请求参数不能为空");
        }
    }


}
